<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-3-18
 * Time: 10:22
 */

namespace doumiaoduo\buildform;


use yii\base\Component;
use yii\base\ErrorException;
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;

class BuildForm extends Component{

    private $_config;

    public function __construct($config){
        $this->_config=require(\Yii::getAlias($config));
    }

    public function render($param=[]){
        $template_file=\Yii::getAlias('@app').DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'layouts'.DIRECTORY_SEPARATOR.$this->_config['template'].'.php';


        if(!is_file($template_file)){
            throw new ErrorException(\Yii::t('app','Sorry, the template is not file'));
        }
        $param['form_config']=$this->_config;
        return \Yii::$app->view->renderFile($template_file,$param);
//        return \Yii::$app->view->render('@app/views/layouts/'.$this->_config['template'].'.php',$param);
    }


    public function loadModel($models){
        foreach($this->_config['models'] as $k=>$v){
            $v['model']=$models[$k];
            $this->_config['models'][$k]=$v;
        }
    }

    public function loadData($values){
        if(!\Yii::$app->request->isPost)return false;
        foreach($this->_config['models'] as $k=>$v){
            $v['model']->load($values);
            $this->_config['models'][$k]=$v;
        }
        return true;
    }

    public function loadDefaultValues($skipIfSet = true){
        foreach($this->_config['models'] as $k=>$v){
            $v['model']->loadDefaultValues($skipIfSet);
        }
    }

    public function validate()
    {
        $ret=true;
        foreach($this->_config['models'] as $k=>$v){
            $ret=$v['model']->validate() && $ret;
        }
        return $ret;
    }

    public function ajaxValidate()
    {
        $ret=[];
        foreach($this->_config['models'] as $k=>$v){
            $ret=empty($ret)?ActiveForm::validate($v['model']):ArrayHelper::merge($ret,ActiveForm::validate($v['model']));
        }
        return $ret;
    }

    public function getModel($model_name){
        return ArrayHelper::getValue($this->_config,'models.'.$model_name.'.model');
    }

    public function setItems($model_name,$field_ame,$items){
        $this->setValue($model_name,$field_ame,'items',$items);
    }

    public function setData($model_name,$field_ame,$attr,$items){
        $this->setValue($model_name,$field_ame,$attr,$items);
    }


    public function setOptions($model_name,$field_ame,$options){
        $this->_config['models'][$model_name]['elements'][$field_ame]['options']=ArrayHelper::merge($this->_config['models'][$model_name]['elements'][$field_ame]['options'],$options);
    }

    public function setValue($model_name,$field_ame,$attr,$value){
        $this->_config['models'][$model_name]['elements'][$field_ame][$attr]=$value;
    }


}